<template>
    <div class="dhzn_rolejunior">
        <!-- 合作伙伴 -->
        <div v-if="pageingstate !== 1" class="d_rj-first">
            <!-- 头部的添加 数量 以及搜索 -->
            <div class="d_rj-title br5 bcwh p10">
                <div class="d_rj-t-search mt10">
                    <button type="button" class="bc4a wh p10 br5 mr10 mb10" @click="pageingstate = 1">添加合作伙伴账号</button>
                    <el-form :model="formstate" ref="formstate" label-width="50px">
                        <el-form-item label='筛选'>
                            <el-col :span="3">
                                <el-select v-model="formstate.state">
                                    <el-option label="不限" value=""></el-option>
                                    <el-option label="已冻结" value="0"></el-option>
                                    <el-option label="正常" value="1"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="3">
                                <el-select v-model="formstate.select" @change=";for(var i in formstate) i!=='state' && i!=='select'? formstate[i] = '' : ''">
                                    <el-option label="用户名" value="0"></el-option>
                                    <el-option label="合作伙伴下级" value="1"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="12">
                                <el-input v-if="formstate.select === '0'" v-model="formstate.username" placeholder="请输入用户名后进行搜索" clearable></el-input>
                                <!-- <el-input v-else v-model="formstate.level" placeholder="请输入用户等级进行搜索" clearable></el-input> -->
                                <el-select v-else v-model="formstate.topid" placeholder="请选择合作伙伴搜索下级" clearable>
                                    <!-- <el-option label="合伙人" value="0"></el-option>
                                    <el-option label="合作伙伴" value="1"></el-option>
                                    <el-option label="合作伙伴下级" value="2"></el-option> -->
                                    <el-option v-for="(item,key) in selectlevel" :key="key" :label="item.name+'('+item.level+'级)'" :value="item.id"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="6" class="tc">
                                <el-button type="primary" @click="currentPage=1,pageingstate=2,searchjunior()">搜索</el-button>
                                <el-button type="danger" @click="currentPage=1,pageingstate=0,requesjunior();for(var i in formstate) i!=='state' && i!=='select'? formstate[i] = '' : ''">取消</el-button>
                            </el-col>
                        </el-form-item>
                    </el-form>
                </div>
                <span class='d_rj-t-num tc wh dib br5 p10'><span></span><span v-if='rolestate === 1'>一级</span><span v-else-if='rolestate === 2'>二级</span><span v-else>三级</span>伙伴总数：<span class="f20">{{number}}</span></span>
            </div>
            <!-- <hr> -->
            <!-- 内容也就是数据列表 -->
            <div class="d_rj-list bcwh br5 p10 mt10">
                <!-- <div class="bb1 pr5 pl5 pb5 mb5" v-if="pageingstate===2"><span class="dib bc4a p5 wh br5" @click="pageingstate=0,currentPage=1,requesjunior()">返回</span></div> -->
                <div class="d_rj-ltitle pr5 pl5"><span class="d_rjl-explain f14">查看合作伙伴：</span>
                    <span @click="rolestate=1,currentPage=1,requesjunior()" :class="['wh p5 dib f14 br5 mr2 cup',rolestate===1 ? 'bc4a' : 'bgbe']">一级</span>
                    <span @click="rolestate=2,currentPage=1,requesjunior()" :class="['wh p5 dib f14 br5 mr2 cup',rolestate===2 ? 'bc4a' : 'bgbe']">二级</span>
                    <span @click="rolestate=3,currentPage=1,requesjunior()" :class="['wh p5 dib f14 br5 mr2 cup',rolestate===3 ? 'bc4a' : 'bgbe']">三级</span>
                </div>
                <table class="d_rj-l-table tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>登录密码<br><span class="b00a n f12">*用鼠标查看密码</span></th>
                            <th>上级合伙人</th>
                            <th>级别</th>
                            <th>账号状态</th>
                            <!-- <th>下级合作伙伴</th> -->
                            <th>下级数量<br><span class="b00a n f12">*点击查看看下级合作伙伴</span></th>
                            <th>下级企业</th>
                            <th>普通门店</th>
                            <th>合伙人店铺会员</th>
                            <th>入驻时间</th>
                            <th>所在城市</th>
                            <th>详细地址</th>
                            <th>姓名</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody class="f14">
                        <tr v-for="(item,key) in juniorlist" v-if="item.level>0" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.username}}</td>
                            <td class="d_rlttbody-pwd"><span>{{item.password | filterpwd}}</span><span class="dn b00a">{{item.password}}</span></td>
                            <!-- <td><span class="b00a" @click="pageingstate=2;currentPage=1;examine(item.id)">查看</span></td> -->
                            <td>{{item.topid | filtertopid}}</td>
                            <td>{{item.level}}</td>
                            <td>{{item.state | filterstate}}</td>
                            <td>{{item.subNumber}}</td>
                            <td>{{item.enterpriseNumber}}</td>
                            <td>{{item.generalStoresNum}}</td>
                            <td>{{item.memberNum}}</td>
                            <td>{{item.createTime*1000 | formatDate}} {{item.createTime*1000 | formatDateBehind}}</td>
                            <td>{{item.city}}</td>
                            <td>{{item.address}}</td>
                            <td>{{item.name}}</td>
                            <td>
                                <button type="button" @click="centerDialog=true;for(var i in juniorupdata) i!=='state' ? juniorupdata[i]=item[i] : juniorupdata[i]=String(item[i]);juniorupdata.key=key" class="bc4a wh br5 p5 whn"><i class="el-icon-edit"></i>编辑</button>
                                <button type="button" @click="freeze(item.id,item.state,key)" class="bcfd wh br5 p5 whn">冻结<i class="el-icon-close"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_rj-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

                <!-- 编辑修改的弹窗 -->
                <el-dialog title="修改" :visible.sync="centerDialog" width="30%" center>
                    
                    <el-form :model="juniorupdata" ref="juniorupdata" :rules="rules" label-width="80px">

                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="juniorupdata.username" placeholder="请输入新的用户名" clearable></el-input>
                        </el-form-item>

                        <el-form-item label="登录密码" prop="password">
                            <el-input v-model="juniorupdata.password" placeholder="请输入新的登录密码" clearable></el-input>
                        </el-form-item>

                        <el-form-item label="账号状态">
                            <!-- <el-input v-model="juniorupdata.username" placeholder="请输入新的用户名" clearable></el-input> -->
                            <el-select v-model="juniorupdata.state">
                                <el-option label="冻结" value="0"></el-option>
                                <el-option label="正常" value="1"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="详细地址" prop="address">
                            <el-input v-model="juniorupdata.address" placeholder="请输入新的详细地址" clearable></el-input>
                        </el-form-item>

                    </el-form>

                    <span slot="footer" class="dialog-footer">
                        <el-button @click="centerDialog=false">取消</el-button>
                        <el-button type="primary" @click="updataroles('juniorupdata')">确定</el-button>
                    </span>
                </el-dialog>
            </div>

        </div>
        <!-- 添加 -->
        <div v-else class="d_rj-second bcwh br5">
            <div class="wh bb1 p10 mb10"><span @click="pageingstate = 0" class="bc4a wh br5 dib f14 p10">回列表页</span></div>
            <el-form :model="junioradd" ref="junioradd" :rules="rules" label-width="90px">

                <el-form-item label="用户名" prop="username">
                    <el-col :span="10"><el-input v-model="junioradd.username" placeholder="请输入用户名" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="password" label="登录密码">
                    <el-col :span="10"><el-input v-model="junioradd.password" placeholder="请输入登录密码" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="topid" label="上级">
                    <el-select v-model="junioradd.topid" placeholder="请选择上级(合伙人无上级)" @change="junioradd.level = '';roleswitch()" clearable>
                        <!-- <el-option label="合伙人" value="0"></el-option> -->
                        <el-option v-for="(item,key) in selectlevel" :key="key" :label="item.name+'('+item.level+'级)'" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="level" label="合作级别" clearable>
                    <el-select v-model="junioradd.level" placeholder="请选择合作级别" clearable>
                        <el-option label="一级合作伙伴" value="1" :disabled="junioradd.switch.level === 0 ? false : true "></el-option>
                        <el-option label="二级合作伙伴" value="2" :disabled="junioradd.switch.level === 1 ? false : true"></el-option>
                        <el-option label="三级合作伙伴" value="3" :disabled="junioradd.switch.level === 2 ? false : true"></el-option>
                    </el-select>
                </el-form-item>

                <!-- <el-form-item prop="subNumber" label="下级数量">
                    <el-col :span="10"><el-input v-model="junioradd.subNumber" placeholder="请输入下级合作伙伴数量" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="enterpriseNumber" label="企业数量">
                    <el-col :span="10"><el-input v-model="junioradd.enterpriseNumber" placeholder="请输入下级企业数量" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="generalStoresNum" label="门店数量">
                    <el-col :span="10"><el-input v-model="junioradd.generalStoresNum" placeholder="请输入下级普通门店数量" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item prop="memberNum" label="店会员数">
                    <el-col :span="10"><el-input v-model="junioradd.memberNum" @input="onm" placeholder="请输入合作伙伴店铺会员数" clearable></el-input></el-col>
                </el-form-item> -->

                <el-form-item prop="city" label="所在城市">
                    <el-cascader :options="cityOptions" v-model="junioradd.provinces" @change="changeProvince" clearable></el-cascader>
                </el-form-item>

                <el-form-item prop="address" label="详细地址">
                    <el-col :span="10"><el-input v-model="junioradd.address" :disabled="junioradd.provinces==undefined || junioradd.provinces=='' ? true : false" placeholder="请输入详细地址"></el-input></el-col>
                </el-form-item>

                <el-form-item prop="name" label="伙伴姓名">
                    <el-col :span="10"><el-input v-model="junioradd.name" placeholder="请输入合作伙伴姓名" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="addjunior('junioradd')">提交</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>

<script>
import cityOptions from '../../js/city_data2017_element.js'
const axios = require('axios');
import {formatDate} from '../../js/time.js'
let that;
export default {
    components: {},
    data() {
        return {
            token: '',                          //登录权限令牌
            number: '',                         //总数统计
            rolestate: 1,                      //合伙人不同等级
            pageingstate: 0,                    //不同数据间显示互不影响
            examineid: '',                      //查看下级的分类的id
            selectlevel:{},                     //用来添加修改上级合伙人id使用的
            //查询的绑定值
            formstate:{
                state: '',
                select: '0',
                username: '',
                topid: ''
            },
            // 修改的绑定对象
            juniorupdata: {
                id: '',
                username: '',
                password: '',
                state: '',
                address: ''
            },
            // 添加合伙人
            junioradd:{
                username: '',
                password: '',
                switch:'',
                topid: '',
                level: '',
                city: '',
                address: '',
                name: ''
            },
            rules:{
                username: [
                    {required:true,message:'请输入用户名',trigger:'blur'}
                ],
                password: [
                    {required:true,message:'请输入登录密码',trigger:'blur'}
                ],
                topid: [
                    {required:true,message:'请选择上级',trigger:'change'}
                ],
                level: [
                    {required:true,message:'请选择合作级别',trigger:'change'}
                ],
                subNumber: [
                    {required:true,message:'请输入下级合作伙伴数量',trigger:'blur'}
                ],
                enterpriseNumber: [
                    {required:true,message:'请输入下级企业数量',trigger:'blur'}
                ],
                generalStoresNum: [
                    {required:true,message:'请输入下级普通门店数量',trigger:'blur'}
                ],
                memberNum: [
                    {required:true,message:'请输入合作伙伴店铺会员数量',trigger:'blur'}
                ],
                city: [
                    {required:true,message:'请输入合作伙伴所在城市',trigger:'blur'}
                ],
                address: [
                    {required:true,message:'请输入合作伙伴详细地址',trigger:'blur'}
                ],
                name: [
                    {required:true,message:'请输入合作伙伴姓名',trigger:'blur'}
                ]
            },
            // 请求列表
            juniorlist: [
                {name:'张三',id:'123',password:'456'},
                {name:'张三',id:'123',password:'456'},
                {name:'张三',id:'123',password:'456'},
                {name:'张三',id:'123',password:'456'},
            ],
            centerDialog: false,                //弹窗的状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            cityOptions: cityOptions,
        };
    },
    filters:{
        filterstatus(id){
            if(id === 0){
                id = '合伙人'
            }else if(id === 1){
                id = "合作伙伴"
            }else{
                id = '合作伙伴下级'
            }
            return id
        },
        filterstate(state){
            if(state === 0){
                state = '冻结'
            }else{
                state = '正常'
            }
            return state
        },
        filtertopid(topid){
            that.selectlevel.forEach((item)=>{
                item.id===topid ? topid = item.name : '';
            })
            return topid
        },
        // 时间戳转换
        formatDate(time){
            var date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date,'hh:mm:ss')
        },
        //密码转成星号
        filterpwd(pwd){
            return pwd = pwd.replace(/./g,'*')
        } 
    },
    computed: {},
    watch: {},
    methods: {
        requesjunior(){
            let that = this;
            let data = {current: that.currentPage,size:that.pagesize,level:that.rolestate};
            let updata = JSON.stringify(data);
            axios({    
                method: 'post',
                url: '/api/partner/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                if(resp.data.message === '请求成功'){                   
                    that.juniorlist = resp.data.data
                    that.total = resp.data.code;
                    that.number = resp.data.code;
                }else{return}
            }).catch( err=> {console.log(err)})
        },

        // 拿到全部的上级合伙人
        async requestpartner(){
            let that = this;
            let total = 10;
            for(var o=0;o<2;o++){
                let data = {current: 1,size: total};
                let updata = JSON.stringify(data);
                await axios({    
                    method: 'post',
                    url: '/api/partner/list',
                    headers: {
                        'Content-type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(o === 0){
                        // 用map挑出需要的字段重新组合，选择的上级合作伙伴
                        resp.data.code <= total ? (
                            that.selectlevel = resp.data.data.map((item)=>{
                                return{
                                    id: item['id'],
                                    name: item['name'],
                                    level: item['level'],
                                    num: item['subNumber']
                                }
                            }),o=2,that.requesjunior()
                        ) : total = resp.data.code;
                    }else{
                        that.selectlevel = resp.data.data.map((item)=>{
                            return{
                                id: item['id'],
                                name: item['name'],
                                level: item['level'],
                                num: item['subNumber']
                            }
                        })
                        that.requesjunior()
                    }
                }).catch( err=> {console.log(err)})
            }
            that.selectlevel.sort(
                function paixu(value1,value2){
                return value1.level-value2.level;//替换为value2-value1可实现从大到小排序
            })
            // console.log('重排后的数组',that.selectlevel)
        },

        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            let that = this;
            that.pagesize = val;
            if(that.pageingstate === 0){
                that.requesjunior()
            }else{
                that.searchjunior()
            }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val;
            if(that.pageingstate === 0){
                that.requesjunior()
            }else{
                that.searchjunior()
            }
        },

        // 增加合作伙伴
        addjunior(junform){
            that.$refs[junform].validate((valid)=>{
                if(valid){
                    let data = {}
                    for(var i in that.junioradd) i!=='switch' && i!=='provinces' ? data[i] = that.junioradd[i] : '';
                    // console.log(data)
                    let updata = JSON.stringify(data);
                    axios({
                        method: 'post',
                        url: '/api/partner/add',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.message === '请求成功'){
                            data.id = resp.data.data;
                            that.rolestate===that.junioradd.switch.level && that.juniorlist.length<that.pagesize ? (that.juniorlist.push(data),that.total += 1) : '';
                            that.pageingstate = 0
                            that.$message({
                                message: '成功了！',
                                type: 'success'
                            })
                        }
                    }).catch( err=> {console.log(err)})
                }else{ return console.log('有没填的')}
            })
        },

        // 修改合作伙伴的信息
        updataroles(junupdata){
            that.$refs[junupdata].validate((valid)=>{
                if(valid){
                    let data = {};
                    for(var u in that.juniorupdata) u!=='' ? data[u] = that.juniorupdata[u] : '';
                    let updata = JSON.stringify(data)
                    console.log(data,updata)
                    axios({
                        method: 'post',
                        url: '/api/partner/update',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.message === "请求成功"){
                            for(var o in data) o!=='state' ? that.juniorlist[that.juniorupdata.key][o] = data[o] : that.juniorlist[that.juniorupdata.key][o] = Number(data[o]);
                            that.centerDialog=false;
                            that.$message({
                                message: resp.data.data,
                                type: 'success'
                            })
                        }else{return}
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
        },

        // 一键冻结
        freeze(id,state,key){
            if(state === 0){
                that.$message.error('账号已冻结！请勿重复操作')
            }else{
                let updata = JSON.stringify({id:id,state:0})
                axios({
                    method: 'post',
                    url: '/api/partner/update',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.message === "请求成功"){
                        that.juniorlist[key].state = 0;
                        that.$message({
                            message: resp.data.data,
                            type: 'success'
                        })
                    }else{return}
                }).catch( err=> {console.log(err)})
            }
        },

        // 搜索
        searchjunior(){
            let data = {current: that.currentPage,size:that.pagesize};
            for(var i in that.formstate) i!=='select' && that.formstate[i]!=='' ? data[i] = that.formstate[i] : '';
            let updata = JSON.stringify(data);
            console.log(data,updata)
            axios({
                method: 'post',
                url: '/api/partner/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                if(resp.data.message === '请求成功'){
                    that.juniorlist = resp.data.data;
                    that.total = resp.data.code;
                    resp.data.code === 0 ? (
                        that.$message({
                            message: '暂无符合条件的合作伙伴合作伙伴',
                            type: 'success'
                        })
                    ) : (
                        that.$message({
                            message: '为您找到'+resp.data.code+'位合作伙伴',
                            type: 'success'
                        })
                    );
                    
                }
            }).catch( err=> {console.log(err)})
        },

        // 级联选择器的数据处理
        changeProvince(){
            let that = this;
            that.junioradd.address = ''
            that.junioradd.provinces.forEach(ment => {
                // console.log(ment.substring(ment.length-3))
                if(ment.charAt(ment.length-1) === '市' || ment.substring(ment.length-3) === '行政区' || ment === '台湾省'){
                    that.junioradd.city = ment
                }
                that.junioradd.address += ment
            });
            // console.log(that.junioradd.city)
        },

        // 处理上级分类的携带值，提交数据做前期准备，
        roleswitch(){
            that.selectlevel.forEach((item)=>{
                that.junioradd.topid === item.id ? that.junioradd.switch = item : '';
            })
            // console.log(that.junioradd.switch.level)
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requestpartner()
			}).catch( err=> {})
        }
    },
    created() {
        let that = this;
        // that.token = JSON.parse(sessionStorage.getItem('token'))
        // that.requestpartner()
        
    },
    mounted() {
        let that = this;
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_rolejunior{
    width: 100%;
    /* background-color: #ffffff; */
}
.d_rj-first,.d_rj-second{
    height: 100%;
}
/* .d_rj-title{
    padding: 10px;
    background-color: #ffffff;
} */
.d_rj-title{
    display: flex;
    justify-content: space-between;
    box-shadow: 0 0 2px #919191;
}
/* 搜索添加 */
.d_rj-t-search{
    width: 100%;
}

.d_rj-t-num{
    vertical-align:top;
    width: 160px;
    height: 90px;
    line-height: 90px;
    background-color: #1BCAFF;
    box-shadow: 1px 0 3px #bebebe;
}
/* 列表 */
.d_rj-list{
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    height: calc(100% - 169px);
    box-shadow: 0 0 2px #919191;
    /* border-right: 1px solid #919191;
    border-bottom: 1px solid #919191;
    border-left: 1px solid #919191; */
}
.d_rj-ltitle{
    /* border-bottom: 1px solid #cccccc; */
}
.d_rj-l-table{
    width: 100%;
    color: #666666;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid  #e0e0e0;
    border-collapse: collapse;
}
.d_rj-l-table thead tr,.d_rj-l-table tbody tr:hover{
    background-color: #F2F2F2;
}
.d_rj-l-table th, .d_rj-l-table td{
    min-height: 50px;
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_rlttbody-pwd:hover span:nth-child(1){
    display: none;
}
.d_rlttbody-pwd:hover span:nth-child(2){
    display: block;
}
/* 分页 */
.d_rj-block{
    margin-top: auto;
}
</style>